package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:ZouChou
 * @Description:
 * @Date:Created in 14:28 2024/5/5
 * @Modified By:
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

//    @Scheduled(cron = "0 * * * * ?")//每分钟执行一次
    public void processTimeOutOrder(){
        log.info("处理超时订单");

        List<Orders> byStatusAndOrderTime = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (byStatusAndOrderTime != null && byStatusAndOrderTime.size() > 0){
            for (Orders orders : byStatusAndOrderTime) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }


    }

//    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨一点执行一次
    public void processCancelOrder(){
        log.info("处理自动取消订单");

        List<Orders> byStatusAndOrderTime = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if (byStatusAndOrderTime != null && byStatusAndOrderTime.size() > 0){
            for (Orders orders : byStatusAndOrderTime) {
                orders.setStatus(Orders.COMPLETED);
                orders.setCancelReason("订单超时，自动完成");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }
}
